<template>
  <div v-drag>
    <div @click="closePopup(false)" class="mask"></div>
    <div class="edit_box" v-loading="loading">
      <div class="box_head">
        <p>{{ mid ? (Boolean(mid&&!isModify)?'查看':'修改') : '新增' }}进货单</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">
        <div class="line">
          <span class="lab"><i class="mark_icon">*</i>司机名称：</span>
          <div :class="{'error_border':tip_num==='siji'}">
            <el-input
              :disabled="Boolean(mid&&!isModify)"
              @input="setTip('','')"
              placeholder="司机名称"
              type="text"
              v-model.trim="driverName"></el-input>
          </div>
        </div>
        <div class="line">
          <span class="lab"><i class="mark_icon">*</i>司机手机号：</span>
          <div :class="{'error_border':tip_num==='phone'}">
            <el-input
              :disabled="Boolean(mid&&!isModify)"
              :maxlength="11"
              @input="setTip('','')"
              onKeypress="return(/[\d.]/.test(String.fromCharCode(event.keyCode)))"
              placeholder="司机手机号" type="text"
              v-model.number="driverPhone"></el-input>
          </div>
        </div>
        <div class="line">
          <span class="lab"><i class="mark_icon">*</i>车牌号：</span>
          <div :class="{'error_border':tip_num==='car'}" >
            <el-input
              :disabled="Boolean(mid&&!isModify)"
              @input="setTip('','')"
              placeholder="车牌号"
              type="text"
              v-model.trim="plateNumber"></el-input>
          </div>
        </div>
        <div class="line" v-if="!isModify">
          <span class="lab"><i class="mark_icon">*</i>仓库：</span>
          <div :class="{'error_border':tip_num==='cangku'}">
            <el-select :disabled="Boolean(mid&&!isModify)" placeholder="请选择仓库" v-model="warehouseId" :popper-append-to-body="false" value-key="id">
              <el-option
                :key="item.id"
                :label="item.name"
                :value="item.id"
                v-for="(item,index) in warehouseList">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="line">

          <div style="width: 100%">
            <div class="lab pro_lab">
              <p v-if="!mid">
                <i class="common_btn el-icon-delete" @click="clearNum()"></i>
                <i @click="addVos()" class="el-icon-circle-plus-outline addlist" v-if="!Boolean(mid&&!isModify)"></i>
              </p>
            </div>
            <div class="line_item" v-for="(item,index) in itemList" >
              <div :class="{'error_border':tip_num===index}">
                <el-select :disabled="Boolean(mid && isModify)"
                           filterable placeholder="请选择商品" v-model="item.productId"
                           value-key="id" @focus="getIndex($event,index)">
                  <span v-if="item.productId == ''">
                  <el-option
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    v-for="(item,index) in productList">
                  </el-option>
                  </span>

                  <span v-else>
                  <el-option
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    v-for="(item,index) in finalProductList">
                  </el-option>
                  </span>

                </el-select>
              </div>
              <div>
<!--                onKeypress="return(/[\d.]/.test(String.fromCharCode(event.keyCode)))"-->
                <el-input :disabled="Boolean(mid&&!isModify)"
                          placeholder="商品数" type="number" v-model="item.numbers" min="1">
                  <template slot="prepend">商品数</template>
                </el-input>
              </div>
              <div>
<!--                onKeypress="return(/[\d.]/.test(String.fromCharCode(event.keyCode)))"-->

                <el-input :disabled="Boolean(mid&&!isModify)"
                          placeholder="回收数" type="number" v-model="item.returnNumber" min="0">
                  <template slot="prepend">回收数</template>
                </el-input>
              </div>
              <span>
                <i @click="delVos(index)" class="el-icon-remove-outline" v-if="!item.id&&itemList.length>1"></i>
              </span>
            </div>
          </div>
        </div>
        <p class="error_line">{{ infoTip }}</p>
      </div>
      <div class="box_foot" v-if="!mid||(mid&&isModify)">
        <span @click="closePopup(false)">取消</span>
        <span @click="confirmEdit">确定</span>
      </div>
    </div>
  </div>
</template>

<script>
  import {getAllWarehouse} from "@/api/basic/warehouse";
  import {listAllData} from "@/api/config/product";
  import {addPurchaseOrder, getPurchaseOrderDetail, updatePurchaseOrder} from "@/api/basic/warehouse/purchaseOrder";
  import {restUrl} from "../../../../url";
  import commons from "@/utils/common";
  import {judgeRole} from "@/utils/warehouseAuth";

  export default {
    props: ['mid', 'isModify'],
    data() {
      return {
        param: {folder: 'water'},
        uploadUrl: restUrl + '/common/upload',
        driverName: '',
        driverPhone: '',
        plateNumber: '',
        numbers: 0,
        returnNumber: 0,
        warehouseId: '',
        productId: '',
        parentMenu: [],
        proStatus: 1,
        warehouseList: [],
        productList: [],
        finalProductList:[],
        isFinal:false,
        itemList: [],
        backupsList: [],
        infoTip: '',
        tip_num: '',
        loading: false,

      }
    },
    mounted() {
      let roleHouse = judgeRole();
      this.warehouseList = roleHouse.list;
      this.warehouseId = roleHouse.id;
      this.productData();
      if (this.mid) {
        this.getDetail();
      } else {
        this.addVos();
      }
    },
    methods: {
      getDetail() {
        let that = this;
        this.loading = true;
        getPurchaseOrderDetail(that.mid).then(res => {
          if (res) {
            that.setData(res);
          }
          that.loading = false;
        }).catch((e) => {
          that.loading = false;
        });
      },


      //仓库列表
      warehouseData() {
        let that = this;
        getAllWarehouse('').then(res => {
          that.warehouseList = res ? res : [];
        }).catch((e) => {
          that.warehouseList = [];
        });
      },

      //仓库商品列表
      productData(data) {
        let queryParams = {}
        if(data) {
          queryParams.productIds = data;
        }
        let that = this;
        listAllData(queryParams).then(res => {
          that.productList = res ? res : [];
          if(!that.isFinal) {
            that.finalProductList = res ? res : [];
            that.isFinal = true;
          }
        }).catch((e) => {
          that.productList = [];
          that.finalProductList = [];
        });
      },
      getIndex(e,index) {
        this.itemList[index].productId = '';
        this.getNewAllProduct();
      },
      getNewAllProduct() {
        // 重新获取列表
        let arr = []
        this.itemList.forEach((item,index)=> {
          if(item.productId != '') {
            arr.push(item.productId)
          }
          return arr
        })
        arr = arr.join(',')
        this.productData(arr);
      },

      setData(obj) {
        this.driverName = obj.driverName;
        this.driverPhone = obj.driverPhone;
        this.plateNumber = obj.plateNumber;
        this.warehouseId = obj.warehouseId;
        this.returnNumber = obj.returnNumber;
        this.itemList = obj.orderDetailVos;
        this.backupsList = JSON.parse(JSON.stringify(obj.orderDetailVos));
      },


      // 确认编辑
      confirmEdit() {
        if (this.driverName === '') {
          this.setTip('siji', '请输入司机名称！');
        } else if (this.driverPhone === '' || (!commons.judgePhone(this.driverPhone))) {
          this.setTip('phone', '请输入正确的手机号!');
        } else if (this.plateNumber === ''|| (commons.judgeCarID(this.plateNumber))) {
          this.setTip('car', '请输入正确的车牌号！');
        } else if (this.warehouseId === '') {
          this.setTip('cangku', '请选择仓库！');
        } else {
          //判断数量和商品
          this.judgeItemList();
        }
      },
      //检验
      judgeItemList() {
        let that = this;
        var proLIndex = that.itemList.length - 1;
        var proLenth = that.itemList.length;
        for (let i = 0; i < proLenth; i++) {
          if (that.itemList[i].productId == '') {
            this.setTip(i, '请选择商品或者删除不需要的商品!');
            return;
          }else if(that.itemList[i].numbers == '' || that.itemList[i].numbers <1) {
            this.setTip(i, '商品数需大于1!');
            return;
          }else if(that.itemList[i].returnNumber === '') {
            this.setTip(i, '请输入回收数!');
            return;
          }
          else {
            if (proLIndex == i) {
              this.setTip('', '');
              that.sendInfo();
            }
          }
        }
      },

      sendInfo() {
        let that = this;
        that.loading = true;
        let data = {
          driverName: that.driverName,
          driverPhone: that.driverPhone,
          plateNumber: that.plateNumber,
          warehouseId: that.warehouseId,
          purchaseOrdersDetailVos: that.itemList,
        };
        if (that.mid) {
          data.id = that.mid;
          updatePurchaseOrder(data).then(res => {
            that.closePopup(true);
            that.$message.success({
              message:'操作成功！',
              duration:1500
            });
            that.loading = false;
          }).catch((e) => {
            that.loading = false;
          });
        } else {
          addPurchaseOrder(data).then(res => {
            that.closePopup(true);
            that.$message.success({
              message:'操作成功！',
              duration:1500
            });
            that.loading = false;
          }).catch((e) => {
            that.loading = false;
          });
        }
      },

      isEnough(data) {
        let num = 0;
        let that = this;
        for (let i = 0; i < data.length; i++) {
          if (data[i].productId) {
            num += data[i].numbers;
            if (!data[i].numbers){
              return false
            }
          } else {
            if (data.length > 1) {
              that.delVos(i);
              i--
            }
          }
        }
        return Boolean(num);
      },
      clearNum() {
        this.itemList = [];
        let obj = {numbers:1, productId: '', returnNumber: 0}
        this.itemList.push(obj);
      },
      addVos() {
        // this.checkList();
        let data = {
          numbers: 1,
          productId: '',
          returnNumber: 0
        };
        this.itemList.push(data);
        this.backupsList.push(JSON.parse(JSON.stringify(data)))
      },

      delVos(index) {
        this.itemList.splice(index, 1);
        this.backupsList.splice(index, 1)
      },


      setTip(num, text) {
        this.tip_num = num;
        this.infoTip = text
      },

      // 关闭
      closePopup(refresh) {
        this.$emit('listenToChild', {refresh: refresh})
      }
    },
  }
</script>

<style scoped>
  .pro_lab {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .line_item {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 10px;
    width: 100%;
  }

  .line_item:first-child {
    margin-top:0
  }

  .line .line_item > div {
    width: 29% !important;
  }

  .line .line_item > span {
    display: block;
    width: 30px;
  }

  .line .line_item i, .addlist {
    font-size: 25px;
    color: #6687f9;
    cursor: pointer;
  }

  .common_btn {
    font-size: 24px;
    cursor: pointer;
    color: #6687f9;
    margin-right: 5px;
  }

  .delSingle {
    color: #e40000 !important;
  }
</style>
